package com.pdh.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: 彭_德华
 * @Date: 2021-09-15 19:38
 */
public class DispatcherServlet extends HttpServlet {

    // 重写init()初始化方法
    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.获取配置文件路径
        String path = config.getInitParameter("contentConfigLocation"); //在web.xml文件中配置
        //2.加载配置文件信息
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        //3.加载配置文件
        HandlerMapping.load(is);
    }

    @Override //直接处理了post和get请求
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取用户请求uri /xx.do
        String uri = req.getRequestURI();

        //2.获取请求对应的方法
        HandlerMapping.MVCMapping mapping = HandlerMapping.get(uri);
        if(mapping == null){
            resp.sendError(404,"MVC:映射地址不存在"+uri);
            return;
        }

        //3.获取方法对应的参数
        Object obj = mapping.getObj(); // 类对象
        Method method = mapping.getMethod(); // 方法
        Object result = null;
        try {
            // 执行（执行的是对应的controller方法）
            result = method.invoke(obj, req, resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //4.向前台去回复结果
        switch (mapping.getType()){
            case TEXT:
                resp.getWriter().write((String) result); // 返回结果（文本）
                break;
            case VIEW:
                resp.sendRedirect((String) result); //跳转页面
                break;
        }
    }
}
